package com.oss.job;

import java.util.List;

import org.joda.time.DateTime;
import org.quartz.JobExecutionContext;

import com.eova.common.base.BaseModel;
import com.eova.common.utils.xx;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.mysgr.zoom.model.DataLog;
import com.mysgr.zoom.model.DeviceMng;
import com.mysgr.zoom.model.DeviceParam;

import com.mysgr.mod.ModTcpM;
import com.mysgr.utils.id.SgrId;

/**
 * 每分钟执行
 *
 * @author Jieven
 * @date 2014-7-7
 */
public class IotModTcpM extends AbsJob {

	@Override
	protected void process(JobExecutionContext context) {
		String log_id = null;
		String dev_ip = null;
		String dev_id = null;
		String res_data = null;
		
		int port = 0;

		DeviceMng tmpdm = DeviceMng.dao.findFirst("select * from t_device_mng where status='1' order by upd_time ");

		if (xx.isEmpty(tmpdm)) {
			try {
				throw new Exception("没有找到需要监控的设备记录!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		dev_ip = tmpdm.getDevIp();

		if (dev_ip == null)
			dev_ip = "localhost";

		port = Integer.parseInt(tmpdm.getDevPort());
		tmpdm.set("upd_time", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
		tmpdm.update();

		dev_id = tmpdm.getDevId();
		
		System.out.println("定时发送监控指令");

		List<DeviceParam> dps = DeviceParam.dao.find("select * from t_device_param where dev_id=? and mon_flag='1'",
				dev_id);
		DataLog dl = new DataLog();
		// 循环根据数据参数采集数据并记录
		for (DeviceParam dp : dps) {
			String param_id = dp.getParamId();
			String data_addr = dp.getDataAddr();
			String data_name = dp.getDataName();
			String data_type = dp.getDataType();
			String max_val = dp.getMaxVal();
			String min_val = dp.getMinVal();
			//int data_num  = dp.getInt("data_num");
			
	
			try {
				 res_data=ModTcpM.readByTCP(dev_ip, port, data_type, Integer.parseInt(data_addr), 1, 1);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				log_id = SgrId.id("CARDID");
				System.out.println(log_id);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dl.set("log_id", log_id);
			dl.set("dev_id", dev_id);
			dl.set("data_addr", data_addr);
			dl.set("data_val", res_data);
			dl.set("param_id", param_id);
			dl.set("log_date", DateTime.now().toString("yyyy-MM-dd"));
			dl.set("log_time", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
			dl.save();
		}
	}

}
